/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.module.upms.server.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.lambkit.Lambkit;
import com.lambkit.common.service.LambkitModelServiceImpl;
import com.lambkit.common.service.LambkitService;
import com.lambkit.component.shiro.ShiroManager;
import com.lambkit.db.sql.column.Example;
import com.lambkit.module.upms.sql.UpmsUserPermissionSqlBuilder;
import com.lambkit.module.upms.model.UpmsPermissionModel;
import com.lambkit.module.upms.model.UpmsUserModel;
import com.lambkit.module.upms.model.UpmsUserPermissionModel;
import com.lambkit.module.upms.model.UpmsUserRoleModel;
import com.lambkit.module.upms.server.service.*;
import com.lambkit.common.service.Service;

import java.util.List;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date 2018-10-25
 * @version 1.0
 * @since 1.0
 * ${tbcnn}
 */
@Service
@LambkitService
public class UpmsUserPermissionModelServiceImpl extends LambkitModelServiceImpl<UpmsUserPermissionModel> implements UpmsUserPermissionModelService {
	
	private UpmsUserPermissionModel DAO = null;
	
	public UpmsUserPermissionModel dao() {
		if(DAO==null) {
			DAO = Lambkit.singleton(UpmsUserPermissionModel.class);
		}
		return DAO;
	}
	
	public int permission(JSONArray datas, UpmsUserModel user) {
        for (int i = 0; i < datas.size(); i ++) {
            JSONObject json = datas.getJSONObject(i);
            if (json.getBoolean("checked")) {
                // 新增权限
                UpmsUserPermissionModel upmsUserPermission = new UpmsUserPermissionModel();
                upmsUserPermission.setUserId(user.getUserId());
                upmsUserPermission.setPermissionId(json.getLongValue("id"));
                upmsUserPermission.setType(json.getInteger("type"));
                upmsUserPermission.save();
            } else {
                // 删除权限
                Example upmsUserPermissionExample = UpmsUserPermissionSqlBuilder.create()
                        .andPermissionIdEqualTo(json.getLongValue("id"))
                        .andTypeEqualTo(json.getInteger("type")).example();
                delete(upmsUserPermissionExample);
            }
        }
        ShiroManager.me().reloadAuthorizing(user.getUsername());
        return datas.size();
    }
	
	public int permission(JSONArray datas, Long id) {
        for (int i = 0; i < datas.size(); i ++) {
            JSONObject json = datas.getJSONObject(i);
            if (json.getBoolean("checked")) {
                // 新增权限
                UpmsUserPermissionModel upmsUserPermission = new UpmsUserPermissionModel();
                upmsUserPermission.setUserId(id);
                upmsUserPermission.setPermissionId(json.getLongValue("id"));
                upmsUserPermission.setType(json.getInteger("type"));
                upmsUserPermission.save();
            } else {
                // 删除权限
                Example upmsUserPermissionExample = UpmsUserPermissionSqlBuilder.create()
                        .andPermissionIdEqualTo(json.getLongValue("id"))
                        .andTypeEqualTo(json.getInteger("type")).example();
                delete(upmsUserPermissionExample);
            }
        }
        return datas.size();
    }

	@Override
	public boolean hasRule(Long userId, Long ruleid) {
		// TODO Auto-generated method stub
		if(UpmsUserRoleModel.service().hasRole(userId, 1L)) {
			return true;
		}
		UpmsUserPermissionModel uup = UpmsUserPermissionModel.service().dao().findFirst(dao().getSqlPara("upms.hasRuleOfUserId", userId, ruleid));
		return uup!=null ? true : false;
	}
	
	public boolean hasRule(Integer roleid, Integer ruleid) {
		if (roleid == 1) {
			return true;
		}
		UpmsUserPermissionModel uup = UpmsUserPermissionModel.service().dao().findFirst(dao().getSqlPara("upms.hasRule", roleid, ruleid));
		return uup!=null ? true : false;
	}

	@Override
	public boolean hasRule(Long userId, String permission) {
		// TODO Auto-generated method stub
		UpmsPermissionModel record = UpmsPermissionModel.service().dao().findFirst(dao().getSqlPara("upms.getRuleOfUserIdAndRuleName", userId, permission));
		return record!=null ? true : false;
	}

	@Override
	public boolean lacksRule(String permission) {
		// TODO Auto-generated method stub
		Example upc = UpmsPermissionModel.sql().andPermissionValueEqualTo(permission).example();
		UpmsPermissionModel upmsPermission = UpmsPermissionModel.service().findFirst(upc);
		if(upmsPermission==null || upmsPermission.getStatus()==0) {
			return false;
		}
		return true;
	}

	@Override
	public boolean hasAnyRules(Long userId, String permissions) {
		// TODO Auto-generated method stub
		permissions = permissions.startsWith(",") ? permissions.substring(1) : permissions;
		permissions = permissions.endsWith(",") ? permissions.substring(0, permissions.length()-1) : permissions;
		Kv data = Kv.by("userid", userId).set("names", permissions.split(","));
		List<UpmsPermissionModel> record = UpmsPermissionModel.service().dao().find(dao().getSqlPara("upms.getRuleOfUserIdAndRuleNames", data));
		return record != null && record.size() > 0 ? true : false;
	}

	@Override
	public boolean hasAllRules(Long userId, String permissions) {
		// TODO Auto-generated method stub
		permissions = permissions.startsWith(",") ? permissions.substring(1) : permissions;
		permissions = permissions.endsWith(",") ? permissions.substring(0, permissions.length()-1) : permissions;
		Kv data = Kv.by("userid", userId).set("names", permissions.split(","));
		List<UpmsPermissionModel> rules = UpmsPermissionModel.service().dao().find(dao().getSqlPara("upms.getRuleOfUserIdAndRuleNames", data));
		permissions = "," + permissions + ",";
		if(rules!=null && rules.size() > 0) {
			for (UpmsPermissionModel rule : rules) {
				permissions.replace(","+rule.getName()+",", ",");
			}
			if(",".equals(permissions)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
